package Bitcoin::Exchange::BTCE;

use strict;
use JSON;
use LWP::UserAgent;
use Digest::SHA "hmac_sha512_hex";

sub new {
	my ($class, %params) = @_;
	
	my $ua = LWP::UserAgent->new();
	$ua->timeout(defined($params{"timeout"}) ? $params{"timeout"} : 10);
	$ua->agent(defined($params{"agent"}) ? $params{"agent"} : "btrader");
	
	my $self = bless(
			{
				"puburl"	=>	defined($params{"puburl"})
									? $params{"puburl"}
									: "https://btc-e.com/api/2",
									
				"pvturl"	=>	defined($params{"pvturl"})
									? $params{"pvturl"}
									: "https://btc-e.com/tapi",

				"key"		=>	$params{"key"},
				"secret"	=>	$params{"secret"},
				"nonce"		=>	time(),
				"ua"		=>	$ua,
			},
			$class
		);
		
	return($self);
}

sub getReqString {
	my ($self) = @_;
	
	return($self->{"req"});
}

sub getResString {
	my ($self) = @_;
	
	return($self->{"res"});
}

sub getErrString {
    my ($self) = @_;

        return($self->{"err"});
}

sub getErrorMsg {
	my ($self) = @_;
	
	return($self->{"errormsg"});
}

sub callPub {
	my ($self, $method, $pair) = @_;
	
	$self->{"req"} = $pair."/".$method;
	
	my $res = $self->{"ua"}->get(
			$self->{"puburl"}."/".$self->{"req"},
		);
		
	if ($res->is_success()) {
	        $self->{"res"} = $res->content();
		if (my $json = JSON->new()->decode($self->{"res"})) {
			return($json);
		} else {
			return(0);
		}
	} else {
		$self->{"errormsg"} = "Request \"".$method."\" with pair \"".$pair."\" failure";
		return(0);
	}
}

sub callPvt {
	my ($self, $method, %params) = @_;
	
	$self->{"err"} = undef;
	$self->{"nonce"}++;
	$self->{"req"} = "method=".$method."&nonce=".$self->{"nonce"};
	
	foreach my $key (keys(%params)) {
		$self->{"req"} .= "&".$key."=".$params{$key};
	}
	
	my $sign = hmac_sha512_hex($self->{"req"}, $self->{"secret"});
	
	my $res = $self->{"ua"}->post(
			$self->{"pvturl"},
			"Key"		=>	$self->{"key"},
			"Sign"		=>	$sign,
			"Content"	=>	$self->{"req"},
		);
		
	if ($res->is_success()) {
	        $self->{"res"} = $res->content();
		if (my $json = JSON->new()->decode($self->{"res"})) {
			if ($json->{"success"}) {
				return($json->{"return"});
			} else {
			        $self->{"err"} = $json->{"error"};
				$self->{"errormsg"} = "Request \"".$method."\" error - ".$json->{"error"};
			}
		} else {
			return(0);
		}
	} else {
		$self->{"errormsg"} = "Request \"".$method."\" failure";
		return(0);
	}
}

1;
